//
//  YunCamHttp.m
//  p2pcam264
//
//  Created by tutk on 3/23/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import <IOTCamera/Camera.h>
#import "CommonHttp.h"

#import <CommonCrypto/CommonDigest.h>

//#if defined(P2PPETWANT)
#if 1

#ifndef SHOW_TIP
#define SHOW_TIP
#endif

#endif

////#define Asynchronous_req

#define TIMEOUT_INTERVAL_SEC    15.0


#define ENCRYPTION_SALT         @"FX15"


@interface CommonHttp ()

@end

@implementation CommonHttp

@synthesize delegate;
@synthesize recvBool;
@synthesize encryptionSalt;
@synthesize securityCode;

- (id)init {
    self = [super init];
    if (self) {
        // Custom initialization

        isAlert = NO;
        
        encryptionSalt = ENCRYPTION_SALT;
    }
    
    return self;
}

- (void)dealloc
{
    self.delegate = nil;
    self.encryptionSalt = nil;
    self.securityCode = nil;
    [super dealloc];
}

- (BOOL)urlContainIllegalString:(NSString *)str {
    
    NSCharacterSet *errorCharStr = [NSCharacterSet
                                    
                                    characterSetWithCharactersInString:@" ~!@#$%^&*+?/="];
    
    NSRange range = (NSRange){65535,0};
    
    range = [str rangeOfCharacterFromSet:errorCharStr];
    
    if (range.length > 0) {
        
        return YES;
        
    }
    return NO;
}

- (BOOL)urlContainIllegalString2:(NSString *)str {
    
    NSCharacterSet *errorCharStr = [NSCharacterSet
                                    
                                    characterSetWithCharactersInString:@" ~!#$%^&*+?/="];
    
    NSRange range = (NSRange){65535,0};
    
    range = [str rangeOfCharacterFromSet:errorCharStr];
    
    if (range.length > 0) {
        
        return YES;
        
    }
    return NO;
}

- (NSString *)md5:(NSString *)str
{
    NSLog(@"md5 str:%@", str);
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    
    for (int i=0; i<16; i++) {
        NSLog(@"%x    ", result[i]);
    }
    
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}


#ifdef Asynchronous_req
/**
 *
//异步请求的代理方法
 *
 **/

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
    NSLog(@"connection didReceiveResponse response:%@",[res allHeaderFields]);
    ////self.receiveData = [NSMutableData data];
    
}

//接收到服务器传输数据的时候调用，此方法根据数据大小执行若干次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"connection didReceiveData data:%@", data);
    if (data) {
        NSString *stringFromUnichar2 = [NSString stringWithCString:(char*)[data bytes] length:[data length] / sizeof(char)];
        
        NSLog(@"%@", stringFromUnichar2);
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.delegate) [self.delegate didChangeDevUrl:nil];
    });
    
    ////[self.receiveData appendData:data];
}

//数据传完之后调用此方法
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"connectionDidFinishLoading connection:%@", connection);
    //NSString *receiveStr = [[NSString alloc] initWithData:self.receiveData encoding:NSUTF8StringEncoding];
    //NSLog(@"%@",receiveStr);
}

//网络请求过程中，出现任何错误（断网，连接超时等）会进入此方法
-(void)connection:(NSURLConnection *)connection
 didFailWithError:(NSError *)error
{
    if (error != NULL) {
        NSLog(@"error >>>>");

        //NSLog(@"connection didFailWithError error:%@",[error localizedDescription]);

    }
}
#endif

- (void)falseRecvDataToProcess:(NSString *)error {
    
    if (isAlert) {
        NSLog(@"falseRecvDataToProcess isAlert:%d", isAlert);
    } else {
        NSLog(@"falseRecvDataToProcess begin");
        isAlert = YES;
        NSString *err;
        err = (error == nil) ? NSLocalizedString(@"Please reconnect", @"") : error;
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"The return value error", @"") message:err delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK", nil), nil];
        [alert setAlertViewStyle:UIAlertViewStyleDefault];
        [alert show];
        [alert release];
        
        NSLog(@"falseRecvDataToProcess end");
    }
}

- (void)nullRecvDataToProcess:(NSString *)error {
    
    NSLog(@"nullRecvDataToProcess");
    return;
    
    if (isAlert) {
        NSLog(@"nullRecvDataToProcess isAlert:%d", isAlert);
    } else {
        NSLog(@"nullRecvDataToProcess begin");
        isAlert = YES;
        NSString *err;
        err = (error == nil) ? NSLocalizedString(@"Please check the network situation", @"") : error;
    
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Obtaining information failed", @"") message:err delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK", nil), nil];
        [alert setAlertViewStyle:UIAlertViewStyleDefault];
        [alert show];
        [alert release];
        
        NSLog(@"nullRecvDataToProcess end");
    }
}

#pragma mark - UIAlertViewDelegate implementation
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"alertView buttonIndex:%ld",(long)buttonIndex);
    if ( buttonIndex == 1 ) {

    } else {

    }
    
    isAlert = NO;
}


- (void)printfVar {


}

- (NSData *)reqHttpGetMode:(NSString *)url {
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    
    NSLog(@"reqHttpGetMode in");
    
    [request setTimeoutInterval:TIMEOUT_INTERVAL_SEC];
    [request setURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"GET"];
    
    NSLog(@"reqHttpGetMode request:%@", request);
    
    NSHTTPURLResponse *urlResponse = nil;
    NSError *error = nil;
    NSData *recervedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    NSLog(@"reqHttpGetMode error:%@", error);
    NSLog(@"reqHttpGetMode urlResponse:%@", urlResponse);
    NSLog(@"reqHttpGetMode recervedData:%@", recervedData);
    
    // check for an error
    if (error != nil) {
        NSLog(@"[error code]:%ld", (long)[error code]);
        //NSLog(@"Error on load = %@", [error localizedDescription]);
        
#ifdef SHOW_TIP
        if (NSURLErrorTimedOut == [error code]) {
//            [[iToast makeText:NSLocalizedString(@"Request timed out, please check the network", @"")] show2];
        } else {
            NSString *str = [NSString stringWithFormat:NSLocalizedString(@"Network anomalies:%ld  please check your network", @""), [error code]];
//            [[iToast makeText:str] show2];

        }
        
#endif
        
        return nil;
    }
    
    // check the HTTP status
    if ([urlResponse isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)urlResponse;
        NSLog(@"httpResponse.statusCode:%ld", (long)httpResponse.statusCode);
        if (httpResponse.statusCode != 200) {
            
#ifdef SHOW_TIP
            NSString *str = [NSString stringWithFormat:NSLocalizedString(@"Server exception:%ld", @""), httpResponse.statusCode];
//            [[iToast makeText:str] show2];
#endif
            
            return nil;
            
        }
        //NSLog(@"Headers: %@", [httpResponse allHeaderFields]);
        
    }
    
    if (recervedData) {
        NSString *stringFromUnichar = [NSString stringWithCharacters:(unichar*)[recervedData bytes] length:[recervedData length] / sizeof(unichar)];
        
        NSString *stringFromUnichar2 = [NSString stringWithCString:(char*)[recervedData bytes] length:[recervedData length] / sizeof(char)];
        
        
        NSLog(@"%@", stringFromUnichar);
        NSLog(@"%@", stringFromUnichar2);
        
        
    } else {
        [self nullRecvDataToProcess:nil];
    }
    
    return recervedData;
}


- (NSData *)reqHttp:(NSString *)url data:(NSData *)postData {
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    
    NSString *postLength=[NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
    NSLog(@"reqHttp postLength:%@", postLength);
    
    [request setTimeoutInterval:TIMEOUT_INTERVAL_SEC];
    [request setURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    
    NSLog(@"reqHttp request:%@", request);
    
    NSHTTPURLResponse *urlResponse = nil;
    NSError *error = nil;
    NSData *recervedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    NSLog(@"reqHttp error:%@", error);
    NSLog(@"reqHttp urlResponse:%@", urlResponse);
    NSLog(@"reqHttp recervedData:%@", recervedData);
    
    // check for an error
    if (error != nil) {
        NSLog(@"error >>>>");

        //NSLog(@"Error on load = %@", [error localizedDescription]);
    }
    
    // check the HTTP status
    if ([urlResponse isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)urlResponse;
        NSLog(@"httpResponse.statusCode:%ld", (long)httpResponse.statusCode);
        if (httpResponse.statusCode != 200) {
        }
        //NSLog(@"Headers: %@", [httpResponse allHeaderFields]);
    }
    
    if (recervedData) {
        NSString *stringFromUnichar = [NSString stringWithCharacters:(unichar*)[recervedData bytes] length:[recervedData length] / sizeof(unichar)];
        
        NSString *stringFromUnichar2 = [NSString stringWithCString:(char*)[recervedData bytes] length:[recervedData length] / sizeof(char)];
        
        
        NSLog(@"%@", stringFromUnichar);
        NSLog(@"%@", stringFromUnichar2);
        
        
    } else {
        [self nullRecvDataToProcess:nil];
    }
    
    return recervedData;
}


- (void)reqHttpAsynchronous:(NSString *)url data:(NSData *)postData {
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    
    NSString *postLength=[NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
    NSLog(@"reqHttpAsynchronous postLength:%@", postLength);
    
    [request setTimeoutInterval:TIMEOUT_INTERVAL_SEC];
    [request setURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    
    NSLog(@"reqHttpAsynchronous request:%@", request);
    
    NSURLConnection *connection = [[[NSURLConnection alloc]initWithRequest:request delegate:self] autorelease];
    
}

- (BOOL)retValueShow:(NSInteger)cmd code:(NSInteger)code {
    BOOL isSuccess = NO;
    
    NSLog(@"retValueShow cmd:%ld code:%ld", (long)cmd, (long)code);
    switch (code) {

        case RET_SUCCESS:
            isSuccess = YES;
            break;
            
        case RET_FAILURE:
            isSuccess = NO;
            
//            [[iToast makeText:[NSString stringWithFormat:@"%@ %ld, %ld", NSLocalizedString(@"ERROR:", @""), (long)cmd, (long)code]] show2];
            
            [self failureToShow:cmd];
            
            break;
            
            
        case RET_INF_ABNORMAL:
            isSuccess = NO;
            
            NSString *str = [NSString stringWithFormat:@"%@  %ld", NSLocalizedString(@"Submit an exception request information", @""), (long)code];
            
//            [[iToast makeText:str] show2];
            
            break;
            
        case RET_RANDOM_NO_USERID:
            isSuccess = NO;
            
//            [[iToast makeText:NSLocalizedString(@"Enter the account does not exist, re-enter after confirmation", @"")] show2];
            
            if ([self.delegate respondsToSelector:@selector(httpReturnErrorPasswordOrAccount)]) {
                
                [self.delegate httpReturnErrorPasswordOrAccount];
            
            } else {
                NSLog(@"RET_RANDOM_NO_USERID ; No respondsToSelector httpReturnErrorPasswordOrAccount");
            }
            
            break;
            
        case RET_ID_PW_WRONG:
            isSuccess = NO;
            
//            [[iToast makeText:NSLocalizedString(@"Account name and password do not match, please re-enter", @"")] show2];
            
            if ([self.delegate respondsToSelector:@selector(httpReturnErrorPasswordOrAccount)]) {
                
                [self.delegate httpReturnErrorPasswordOrAccount];
                
            } else {
                NSLog(@"RET_ID_PW_WRONG ; No respondsToSelector httpReturnErrorPasswordOrAccount");
            }
            break;
            
        case RET_MAIL_ABNORMAL:
            isSuccess = NO;
//            [[iToast makeText:NSLocalizedString(@"Email address is not valid", @"")] show2];
            break;
        case RET_RG_MAIL_INVALID:
            isSuccess = NO;
//            [[iToast makeText:NSLocalizedString(@"Email address is not valid", @"")] show2];
            break;
            
        case RET_RG_USERID_TOKEN:
            isSuccess = NO;
//            [[iToast makeText:NSLocalizedString(@"Account already exists", @"")] show2];
            break;
            
        case RET_RG_MAIL_TOKEN:
            isSuccess = NO;
//            [[iToast makeText:NSLocalizedString(@"Email has been registered", @"")] show2];
            break;
        case RET_CHECKREGED_TOKEN:
            isSuccess = NO;
//            [[iToast makeText:NSLocalizedString(@"Email has been registered", @"")] show2];
            
            /*找回密码:215xx*/
            //RET_FINDPW_NO_MAIL_RECORD = 21501, //找回密码填写的邮箱没记录
            //RET_FINDPW_TOO_OFTEN = 21502; // 找回密码太频繁，1 分钟后再申请
            //RET_FINDPW_MAIL_INVALID = 21503; //邮箱格式不正确
        case RET_FINDPW_NO_MAIL_RECORD:
            isSuccess = NO;
//            [[iToast makeText:NSLocalizedString(@"Email address does not exist", @"")] show2];
            break;
        case RET_FINDPW_TOO_OFTEN:
            isSuccess = NO;
//            [[iToast makeText:NSLocalizedString(@"So frequently, one minute after application", @"")] show2];
            break;
        case RET_FINDPW_MAIL_INVALID:
            isSuccess = NO;
//            [[iToast makeText:NSLocalizedString(@"Email address is not valid", @"")] show2];
            break;
            
            /*设置密码:216xx*/
                      //= 21601, //设置密码输入的原密码不正确
        case RET_OLD_PASSWD_ERROR:
            isSuccess = NO;
//            [[iToast makeText:NSLocalizedString(@"Enter the original password is incorrect", @"")] show2];
            break;
            
        case RET_SELECT_NO_RECORD:
            isSuccess = NO;
            
//            [[iToast makeText:NSLocalizedString(@"Notes does not exist", @"")] show2];
            
            break;
            
        case RET_CHECKPHONE_TOKEN:
            isSuccess = NO;
            
//            [[iToast makeText:NSLocalizedString(@"Phone number has been registered", @"")] show2];
            
            break;
        case RET_RG_RND_ERROR:
            isSuccess = NO;
            
//            [[iToast makeText:NSLocalizedString(@"Phone verification code error", @"")] show2];
            
            break;
            
        case RET_ADDDEV_DEVID_TOKEN:
            isSuccess = YES;
            
            break;
        case RET_ADDDEV_ADDED:
            isSuccess = YES;
            
            break;
            
        case RET_CHECKREGED_UNTOKEN:
            isSuccess = YES;
            
            break;
            
        default:
            isSuccess = NO;
            
            //[[iToast makeText:[NSString stringWithFormat:@"%@ %ld, %ld", NSLocalizedString(@"ERROR:", @""), (long)cmd, (long)code]] show2];

            break;
    }
    
    return isSuccess;
}

- (void)failureToShow:(NSInteger)cmd {
    switch (cmd) {
        case CMD_CMDINF_CODE:
            break;
            
        case CMD_REG_CODE:
            break;
            
        case CMD_RANDOM_CODE:
            
            //[[iToast makeText:NSLocalizedString(@"Account does not exist", @"")] show2];
            
            break;
            
        case CMD_LOGIN_CODE:
            
//            [[iToast makeText:NSLocalizedString(@"Login fail", @"")] show2];
            
            break;
            
        default:
            break;
    }
}

@end
